import { useCall } from '@/components';
import { Select } from 'antd';
import React, { useMemo, useState } from 'react';
import useCompanyOptions from './hooks/useCompanyOptions';

function CompanySearchField(props) {
  const companies = useCompanyOptions();

  const [value, setValue] = useState();
  const onSearch = setValue;
  const onChange = useCall((selectedValue) => {
    if (value !== selectedValue) setValue(null);
    props.onChange?.(selectedValue);
  });

  const options = useMemo(() => {
    const labels = (companies ?? []).flatMap((v) => (v.value === '0' ? [] : [v.label]));
    const valueOptions = value && !labels.includes(value) ? [{ value, label: value }] : [];
    const companyOptions = labels?.map((label) => ({ label, value: label })) ?? [];
    return [...valueOptions, ...companyOptions];
  }, [value, companies]);

  return (
    <Select
      {...props}
      showSearch
      optionFilterProp='label'
      allowClear
      options={options}
      onSearch={onSearch}
      onChange={onChange}
    />
  );
}

export default CompanySearchField;
